package com.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.reggie.common.BaseContext;
import com.reggie.common.R;
import com.reggie.entity.AddressBook;
import com.reggie.service.AddressBookService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 地址簿
 */
@Slf4j
@RestController
@RequestMapping("/addressBook")
public class AddressBookController {
    @Autowired
    private AddressBookService addressBookService;

    /**
     * 新增套餐
     */
    @PostMapping
    public R<AddressBook> addAddress(@RequestBody AddressBook addressBook){
        log.info(addressBook.toString());
        //首先设置当前的用户id 在登录的时候已经给线程的id set
        addressBook.setUserId(BaseContext.getCurrentId());
        //存入数据库
        addressBookService.save(addressBook);
        return R.success(addressBook);
    }

    /**
     * 设置默认地址
     */
    @PutMapping("/default")
    public R<AddressBook> defaultAddress(@RequestBody AddressBook addressBook){
        log.info("设置默认地址id: "+addressBook.getId());
        //is_default 改成1 但是要先把别的都取消了
        addressBookService.setdefault(addressBook.getId());
        return R.success(addressBook);
    }

    /**
     * 展示已有地址
     * @return
     */
    @GetMapping("/list")
    public R<List<AddressBook>> addresslist(){
        LambdaQueryWrapper<AddressBook> lqw = new LambdaQueryWrapper<>();
        lqw.eq(AddressBook::getUserId,BaseContext.getCurrentId());
        lqw.orderByDesc(AddressBook::getUpdateTime);
        List<AddressBook> addressBooks = addressBookService.list(lqw);
        return R.success(addressBooks);
    }

    /**
     * 修改回显以及查找
     */
    @GetMapping("/{id}")
    public R<AddressBook> setterAndFind(@PathVariable Long id){
        LambdaQueryWrapper<AddressBook> lqw = new LambdaQueryWrapper<>();
        lqw.eq(AddressBook::getId,id);
        AddressBook one = addressBookService.getOne(lqw);
        return  R.success(one);
    }

    /**
     * 修改并保存
     */
    @PutMapping()
    public R<String> setterAndSave(@RequestBody AddressBook addressBook){
        addressBookService.updateById(addressBook);
        return R.success("保存成功!");
    }

    /**
     * 删除地址
     */
    @DeleteMapping
    public R<String> delAddress(@RequestParam Long ids){
        addressBookService.removeById(ids);

        return R.success("删除成功!");
    }

    /**
     * 结算时获取默认地址
     */
    @GetMapping("/default")
    public R<AddressBook> getDefault(){
        LambdaQueryWrapper<AddressBook> lqw = new LambdaQueryWrapper<>();
        //查当前用户的地址
        lqw.eq(AddressBook::getUserId,BaseContext.getCurrentId());
        lqw.eq(AddressBook::getIsDefault,1);//为默认的时候
        AddressBook addressBook = addressBookService.getOne(lqw);
        return R.success(addressBook);
    }


}
